package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @ClassName :  UsersApiImpl
 * @Author : Tenebrous
 * @Date: 2020/12/16 19:14
 * @Description : usersAPI实现类
 */
@Service(version = "1.0.0")
public class UsersApiImpl implements UserApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加好友
     *
     * @param users     用户对象
     * @return          字符串
     */
    @Override
    public String saveUsers(Users users) {
        // 校验用户id与朋友id是否存在
        if (users.getUserId() == null || users.getFriendId() == null) {
            // 不存在返回null
            return null;
        }

        Query query = Query.query(Criteria.where("userId").is(users.getUserId()).and("friendId").is(users.getFriendId()));
        // 查找该好友是否存在好友列表中
        Users oldUsers = this.mongoTemplate.findOne(query, Users.class);
        // 判断是否为null
        if (null != oldUsers) {
            //不为null，说明好友存在，返回null
            return null;
        }

        users.setId(ObjectId.get());
        users.setDate(System.currentTimeMillis());

        this.mongoTemplate.save(users);
        return users.getId().toHexString();
    }

    /**
     *
     * @param userId        用户id
     * @return              用户集合
     */
    @Override
    public List<Users> queryAllUsersList(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return this.mongoTemplate.find(query, Users.class);
    }

    /**
     *
     * @param userId    用户id
     * @param page      页码
     * @param pageSize  每页条数
     * @return          分页参数
     */
    @Override
    public PageInfo<Users> queryUsersList(Long userId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);

        List<Users> usersList = this.mongoTemplate.find(query, Users.class);

        PageInfo<Users> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(usersList);
        //不提供总数
        pageInfo.setTotal(0);
        return pageInfo;
    }

}
